import axios from 'axios'
import qs from 'qs'
import config from '../config/config'
import {reqInform, showConfirm} from './notification'
import Cookie from 'js-cookie'
import {hashHistory} from 'dva/router'
import {join,get} from 'lodash'
import { messageInform } from '../utils/notification'
import {getLocalData} from '../utils/globalScope'
import toBase64 from './toBase64'
// 登录跳转的方法
import { customLoginRedirect } from '../utils/redirect_utils'

// 弹窗次数
let confirmCount = 0

const fetch = (options) => {
  let {method = 'post', data, url, auth = Cookie.get(config.cookie.auth),tokenId=localStorage.getItem("tokenId"), timeout = config.reqTimeout } = options
  // 取出headers
  let {headers,reqTimeout} = options;
  //针对个别接口需要加长超时时间
  timeout=reqTimeout?reqTimeout : config.reqTimeout
  headers = headers ? headers : {}
  //解决ie不重新请求问题
  headers = {
    ...headers,
    'adminToken':auth,
    'token': auth,
    'tokenId':tokenId,
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache',
    'Expires': -1
  }

  if (!headers['Content-type']) {
    headers['Content-type'] = 'application/x-www-form-urlencoded';
    if(method.toLowerCase()=='post'){
      headers['Content-type'] = 'application/json';
    }
  }
  const hasUrl = function (arr, url) {
    let flag = false
    arr.map((k, i) => {
      if(url.indexOf(k) !== -1){
        flag = true
      }
    })
    return flag
  }
  const exAuthArr = ['restapi.amap.com', config.requestApiUrl.getValidateImg]
  // 请求headers中移除auth
  if (hasUrl(exAuthArr, url)) {
    delete headers['auth'];
  }

  const exAppIdArr = ['verify/img/get', '/huieryun-identity/', 'restapi.amap.com']

  // 请求headers中增加Application-Key
  if(!hasUrl(exAppIdArr, url)  && !headers["Application-Key"]){
    headers["Application-Key"] = config.appKey;
  }

  //过滤获取经纬度报错问题
  const exAuthArr1 = ['restapi.amap.com'];
  // 请求headers中移除Pragma  Expires
  if (hasUrl(exAuthArr1, url)) {
    delete headers['Pragma'];
    delete headers['Expires'];
    delete headers['unitId'];
  }
   //console.log('headers:', `${url}${options.data ? `?${qs.stringify(options.data)}` : ''}`);
  switch (method.toLowerCase()) {
    
    case 'get':
      return axios.get(`${url}`, {headers, timeout,params:options.data})
    case 'delete':
      return axios.delete(`${url}${options.data ? `?${qs.stringify(options.data)}` : ''}`, {headers, timeout})
    case 'head':
      return axios.head(url, data, {headers, timeout})
    case 'post':
      let newData = data;
      if ('' + headers['Content-type'] === 'application/x-www-form-urlencoded') {
        newData = qs.stringify(data)
      }
      return axios.post(url, newData, {headers, timeout})
    case 'put':
      let putData = data;
      if ('' + headers['Content-type'] === 'application/x-www-form-urlencoded') {
        putData = qs.stringify(data)
      }
      return axios.put(url, putData, {headers, timeout})
    case 'patch':
      return axios.patch(url, data, {headers, timeout})
    default:
      return axios(options)
  }
}

// 跳转到登录
const go2Login = function(isReload){
  confirmCount = 1;
  localStorage.removeItem('antdAdminSiderFold')
  localStorage.removeItem('tokenId')
  sessionStorage.removeItem('SIDER_OPEN_KEY')
  sessionStorage.removeItem('SIDER_SELECTED_KEY')
  // Cookie.remove(config.cookie.userName);
  // Cookie.remove(config.cookie.auth);
  // 移除cookie的值
  Object.keys(config.cookie).map((k, i) => {
    Cookie.remove(config.cookie[k]);
  })
  //企业中心
  if(config.sysType === 'entCenter') {
    localStorage.removeItem(config.userInfoKey);
  }
  // 自定义登录跳转方法
  customLoginRedirect()

  // if(!!isReload){
  //   window.location.reload();
  // }
}

// 检测登录处理, isReload 未登录是否刷新
const checkLogin = function(isReload){
  let auth = Cookie.get(config.cookie.auth);
  console.log(isReload);
  // Cookie中无auth令牌，直接跳转到登录页面
  if(!auth){
    // 跳转登录
    go2Login(isReload)
  }
  return false
}

//isHandCommErr： 是否需要request方法做统一全局报错处理
export default function request (options, isHandCommErr　) {  
  //console.log(options)
  if(!options || !options.url){
    reqInform({
      title: '无效的url',
      description: '请求选项中的url是无效的'
    }, 'error')
    return Promise.reject({resultCode: 1, resultMsg: '无效的url：' + options.url, data: null})
  }
  options.url=( options.url||"").trim()
  options.url = config.apiAppName(options.url, options.app);

  //判断是否存在表情等特殊字符
  // if(options.data){
  //   let emojiData = JSON.stringify(options.data);
  //   var emojiRegRule = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
  //   if (emojiData && emojiData.match(emojiRegRule)) {
  //     messageInform('参数包含了特殊表情符号或其它不可辨识的符号', 'error');
  //     return false;
  //   }
  // }

  return fetch(options).then((response) => {
    //console.log(response)
    let self = this;
    const {statusText, status} = response
    let data = options.isCross ? response.data.query.results.json : response.data
    // Cookie中有auth令牌，表示已登录，但是auth失效的，则弹出窗口提示
    if ('' + 401 === '' + response.status) {
      // 检测是否登录
      checkLogin(false)
      // 若已登录，则检测auth是否失效
      if(confirmCount < 1 ){
        showConfirm().then((cRes) => {
          if('1' === '' + cRes){
            go2Login(false)
          }else{
            confirmCount = 0
          }
        })
        confirmCount ++
      }
      return {resultCode: 0, resultMsg: '登录信息失效提示', data: null}
    }
    window.prevPage=''
    function goLoginPage (data={}) {
      if(data.message){
        data.msg = data.message
      }
      let {success=false,msg=''}=data||{}
      if(location.hash.indexOf('/login')>-1){return false}
      console.log('token----校验',!success && (/token|登录/.test(msg)))
      console.log('(/token|登录/.test(msg)',(/token|登录/.test(msg)))
      if(!success && (/token|登录/.test(msg))){
        window.prevPage=location.href
            hashHistory.push({
              pathname: '/login',
              query: {prevPage:window.prevPage}
            });
      }
    }
    if((!response.data.success && isHandCommErr)) {
      goLoginPage(response.data)
      reqInform({
        title: '系统提示',
        description: response.data.msg || '接口服务故障'
      },'warn',4)
    }
    return {
      resultCode: 0,
      status,
      resultMsg: statusText,
      ...data,
    }
  // }
  }).catch((error) => {
    // const {response = {statusText: 'Network Error'}} = error
    // let errDesc = response.statusText || '接口服务故障';
    // Cookie中有auth令牌，表示已登录，但是auth失效的，则弹出窗口提示 '1' === '' + error.errCode ||
    // if(!error.response){
    //   // go2Login(true);
    //   let p = {
    //     url: `zituo-admin/thirdLogin/getTokenId`,
    //     method: 'POST',
    //     data: {username:localStorage.getItem("username")},
    //   }
    //   fetch(p).then((res)=>{
    //     if(res && res.status == '200'){
    //       localStorage.setItem("tokenId",res.data.tokenId);
    //       return fetch(options);
    //     }
    //   })
    // }
    if ('401' === '' + response.status) {
      // 检测是否登录
      checkLogin(true)
      // 已登录，则检测auth是否失效
      if(confirmCount < 1 ){
        showConfirm().then((cRes) => {
          if('1' === '' + cRes){
            go2Login(true)
            confirmCount = 0;
          }else{
            confirmCount = 0
          }
        })
        confirmCount ++
      }
      return {resultCode: 0, resultMsg: '登录信息失效提示', data: null}
    }else if('' + 406 === '' + response.status) {
      // 如果服务接口响应406，一般是带有sql注入风险的关键字
      errDesc = '查询内容包含sql注入风险的关键字';
    }

    reqInform({
      title: '出现请求错误',
      description: errDesc
    }, 'error')

    return {resultCode: 1, resultMsg: response.statusText, data: null}
  })
}
